<?php

namespace app\api\controller;


use app\common\controller\ApiBase;
use weixin\WXBizDataCrypt;
use think\Request;
use think\Controller;
use think\Db;
use think\Cache;
use app\common\model\User as UserModel;

class User extends ApiBase{
    protected $user_model;

    protected function _initialize()
    {
        parent::_initialize();
        $this->user_model = new UserModel();
    }

    /**
    *获取用户openid
    */
    public function get_openid(){
        $data = $this->request->post();
        $wechatMsg = Db::name('wx_user')->field('appid,appsecret')->where('id',2)->find();
        $code = $data['code'];
        $appid = $wechatMsg['appid'];
        $appsecret = trim($wechatMsg['appsecret']);
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".$appid."&secret=".$appsecret."&js_code=".$code."&grant_type=authorization_code";
        $output = httpRequest($url);
        $result_arr = json_decode($output,true);
        $return = $this->mini_login($data,$result_arr,$appid);
        return $return;
    }

    public function mini_login($data,$result_arr,$appid){
            //新用户注册
            $sessionKey = $result_arr['session_key'];
            $encryptedData = $data['encryptedData'];
            $iv = $data['iv'];
            $signature = $data['signature'];
            $rawData = htmlspecialchars_decode($data['rawData']);

            $signature2 = sha1($rawData.$sessionKey);

            if ($signature2 !== $signature) return json_encode(['status' => -1 , 'error' => 'sign not match']);


            $pc = new WXBizDataCrypt($appid, $sessionKey);
            $errCode = $pc->decryptData($encryptedData, $iv, $data);

            if ($errCode !== 0) {
                print($errCode . "\n");
                
            }

            $data = json_decode($data, true);

            $userinfo_data = [
                'nickname' => $data['nickName'],
                'openid'   => $data['openId'],
                'header_url'   =>empty( $data['avatarUrl'])? '':$data['avatarUrl'] ,
                'sex'   => $data['gender'],
                'city'   => empty($data['city'])?'':$data['city'],
                'province'   => empty($data['province'])?  '':$data['province'],
                'country'   => empty($data['country'])?'':$data['country'],
                'language' => $data['language'],
            ];

            if(Db::name('user')->where('openid',$result_arr['openid'])->find()){
                $userinfo_data['last_login_time'] = date('Y-m-d H:i:s');
                $result = $this->user_model->allowField(true)->save($userinfo_data,['openid' => $result_arr['openid']]);
            }else{
                $userinfo_data['create_time'] = date('Y-m-d H:i:s');
                $result = $this->user_model->allowField(true)->save($userinfo_data);
            }

            if($result){
                $session3rd = randomFromDev(16);
                $userinfo_data['session3rd'] = $session3rd;
                cache($session3rd, $data['openId'] . $sessionKey);

                return json_encode(['status' => 1 , 'msg' => 'login success' , 'userinfo' => $userinfo_data]);
            }
    }

    /*
     * 小程序登录
     * get code 获取对应的数据
     * https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
     * */

    /*
    小程序用户登录接口
    功能: 根据获取的用户数据 openid
    判断用户是否存在
    不存在就注册, 
    存在就调用用户的数据->粉丝+关注
    */
    public function login(){
        // 接收过来的post数据-
        // Request::instance()->post('name'); // 获取某个post变量
        if (Request::instance()->isPost()){
            $open_id = Request::instance()->post('openId');
            // 去数据库查询是否存在改用户的openid
            $is_member = $this->user_model->where(['openid'=>['eq',$open_id]])->select();
            if($is_member){
                return $this->thinkJsonCodeMsg($is_member,200,'已经注册了的老用户');
            }else{
                // 没有注册, 是新用户, 使用信息去注册用户
//                dump(Request::instance()->post());
                $wx_data = Request::instance()->post();
                $wx_user = [
                    'nickname' => $wx_data['nickName'],
                    'openid'   => $wx_data['openId'],
                    'header_url'   =>empty( $wx_data['avatarUrl'])? '':$wx_data['avatarUrl'] ,
                    'sex'   => $wx_data['gender'],
                    'city'   => empty($wx_data['city'])?'':$wx_data['city'],
                    'province'   => empty($wx_data['province'])?  '':$wx_data['province'],
                    'country'   => empty($wx_data['country'])?'':$wx_data['country'],
                    'create_time'   => date('Y-m-d H:i:s', time()),
                    'last_login_time'   =>date('Y-m-d H:i:s', time()),
                    'username'   => '',
                    'password'   => '',
                ];
//                dump($wx_user);
                $reg_wx =   $this->user_model->allowField(true)->save($wx_user);
                if($reg_wx){
                    return $this->thinkJsonCodeMsg($reg_wx,201,'新用户注册成功');
                }else{
                    return $this->thinkJsonCodeMsg($reg_wx,401,'新用户注册失败,请重试');
                }
            }
        }
    }

    /* 局部修改保存信息
     * 基本信息修改 头像 呢称 用户名和密码
     * */
    public function baseinfo($openId){
        $is_member = $this->user_model->where(['openid'=>['eq',$openId]])->select();
        if($is_member){
            if (Request::instance()->isPost()){
                // 编辑数据
                $wx_data = Request::instance()->post();
                $wx_user = [
                    'nickname' => $wx_data['nickName'],
                    'header_url'   =>empty( $wx_data['avatarUrl'])? '':$wx_data['avatarUrl'] ,
                    'city'   => empty($wx_data['city'])?'':$wx_data['city'],
                    'province'   => empty($wx_data['province'])?  '':$wx_data['province'],
                    'country'   => empty($wx_data['country'])?'':$wx_data['country'],
                    'username'   => empty($wx_data['username'])?'':$wx_data['username'],
                    'password'   => empty($wx_data['password'])?'':$wx_data['password'],
                ];
//                dump($wx_user);
                $result =   $this->user_model->allowField(true)->save($wx_user);
                if($result){
                    return $this->thinkJsonCodeMsg('ok',200,'修改数据成功');
                }else{
                    return $this->thinkJsonCodeMsg('error',404,'修改用户数据失败');
                }
            }else{
                // 查看数据
//                dump($is_member);
                return $this->thinkJsonCodeMsg($is_member,'200','ok');
            }
        }else{
            return $this->thinkJsonCodeMsg('error',404,'用户信息不存在');
        }
    }

    /*
     * 用户名校验重复接口
     * */
    public  function check_user($username){
        $is_repeat = $this->user_model->where(['username'=>['eq',$username]])->select();
        if($is_repeat){
            return $this->thinkJsonCodeMsg('repeat',401,'用户名已存在');
        }else{
            return $this->thinkJsonCodeMsg('ok',200,'用户名可用');
        }
    }

    /*
     * 查看/编辑用户其他信息(区别于主要信息) 小程序  底部的修改所有信息
     * POST
     * */
    public function userinfo($openId){
        $is_member = $this->user_model->where(['openid'=>['eq',$openId]])->select();
        if($is_member){
            if (Request::instance()->isPost()){
                // 编辑数据

                $edit_info = $this->user_model->allowField(true)->save(Request::instance()->isPost());
                if($edit_info){
                    return $this->thinkJsonCodeMsg('ok',200,'修改数据成功');
                }else{
                    return $this->thinkJsonCodeMsg('error',404,'修改用户数据失败');
                }
            }else{
                // 查看数据
//                dump($is_member);
                return $this->thinkJsonCodeMsg($is_member,200,'ok');
            }
        }else{
            return $this->thinkJsonCodeMsg('error',404,'用户信息不存在');
        }
    }



    /*
     * 获取粉丝和关注列表 以及 别人打的标签
     *
     * */
    public function fans(){

    }











}